package com.fengpb.friday.conductor.core.execution.mapper;

import com.fengpb.friday.conductor.common.metadata.run.Workflow;
import com.fengpb.friday.conductor.common.metadata.task.Task;
import com.fengpb.friday.conductor.common.metadata.workflow.WorkflowTask;
import com.fengpb.friday.conductor.core.execution.ParametersUtils;
import com.fengpb.friday.conductor.core.execution.TerminateWorkflowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component("HTTP")
public class HttpTaskMapper implements TaskMapper {

    private static final Logger log = LoggerFactory.getLogger(HttpTaskMapper.class);

    private final ParametersUtils parametersUtils;

    public HttpTaskMapper(ParametersUtils parametersUtils) {
        this.parametersUtils = parametersUtils;
    }

    @Override
    public List<Task> getMappedTasks(TaskMapperContext taskMapperContext) throws TerminateWorkflowException {
        log.debug("Create http task in TaskMapperContext {}", taskMapperContext);

        Workflow workflowInstance = taskMapperContext.getWorkflowInstance();
        WorkflowTask taskToSchedule = taskMapperContext.getTaskToSchedule();

        Map<String, Object> input = parametersUtils.getTaskInput(taskToSchedule.getInputParameters(), workflowInstance, null, null);
        Boolean async = (Boolean) input.get("async");
        String taskId = taskMapperContext.getTaskId();

        Task httpTask = new Task();
        httpTask.setTaskType(taskToSchedule.getType());
        httpTask.setTaskDefName(taskToSchedule.getName());
        httpTask.setReferenceTaskName(taskToSchedule.getTaskReferenceName());
        httpTask.setWorkflowInstanceId(workflowInstance.getWorkflowId());
        httpTask.setScheduledTime(System.currentTimeMillis());
        httpTask.setTaskId(taskId);
        httpTask.setInputData(input);
        httpTask.setStatus(Task.Status.SCHEDULED);
        httpTask.setWorkflowTask(taskToSchedule);
        httpTask.setAsync(async);

        return Collections.singletonList(httpTask);
    }
}
